<template>
    <div>
        <!-- 检测记录 -->
        <el-table ref="table" :data="tableData.length > 0 ? tableData : recordsDataSource" :columns="columns" :header-cell-style="{ background: '#fbfbfa', height: '60px' }" style="width: 100%"
            class='tableBottom' @row-click="clickRowHandle" row-key="DataIdentifier" :expand-row-keys="expands">

            <el-table-column label="检测时间" :formatter="dateFormat" prop="CheckBeginTime" align="center" :min-width="180">

            </el-table-column>
            <el-table-column label="用时  (ms)" prop="CheckTotalTime" align="center" :min-width="90">
            </el-table-column>
            <el-table-column label="生产批次" prop="ProductionBatch" align="center" :min-width="150">
            </el-table-column>
            <el-table-column align="center" :min-width="90">

                <template #header>
                    <el-dropdown>
                        <span class="el-dropdown-link mousrPointer">
                            {{ selectOne }}
                            <el-icon>
                                <component :is="mouseOverComponent"></component>
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu class="custom-dropdown-menu">
                                <el-dropdown-item v-for="threeSelect in threeSelects" :key="threeSelect.num" @click="handler(threeSelect)"><span
                                        :class="{ 'dropDown': true, 'dropDownActive': threeSelect.active }">{{ threeSelect.name }}</span></el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
                <template #default="{ row }">
                    <div class="allstyle">
                        <span class="point" :style="{ background: fun(row.CheckResult)?.color }"></span> <span>{{ fun(row.CheckResult)?.showName }}</span>
                    </div>
                </template>
            </el-table-column>
            <!-- <el-table-column label="查看图像" align="center" :min-width="180">
                <template #default="{ row }">
                    <p class="mousrPointer" @click.stop="openPreview(row)" @mouseover="openPreviewImg(row)" @mouseout="closePreviewImg(row)">
                        <ImgIcon v-if='row.CheckImages' :fullColor="row.fullColor ? row.fullColor : '#8C8C8C'"></ImgIcon>
                        <span v-if='!row.CheckImages'>无</span>
                    </p>
                </template>
            </el-table-column> -->
            <el-table-column label="缺陷类型" :min-width="800" :show-header-overflow-tooltip="true">
                <template #header>
                    <el-dropdown>
                        <span class="el-dropdown-link  mousrPointer">
                            {{ selectTwo }}
                            <el-icon>
                                <CaretBottom />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-if="flawLists.length < 1"><span>暂无数据</span></el-dropdown-item>
                                <div v-if="flawLists.length > 0">
                                    <el-dropdown-item v-for="(CheckName, index) in flawLists" :key="index" @click="handler1(CheckName)"><span
                                            :class="{ 'dropDown': true, 'dropDownActive': CheckName?.active }">{{ CheckName.name }}</span></el-dropdown-item>
                                </div>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
                <template #default="{ row }">
                    <span style="float:left">{{ row.CheckItems }}</span>
                    <!-- 
                    <el-tag v-for="tag in row.CheckItems.split(',')" :key="tag" class="ml-3 noLeftMargin" type="warning">
                        {{ tag }}
                    </el-tag> -->
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="previewVisible" @close="resetPreview" class="imageListDialog" width="90%">
            <!-- <p style="color:#fff">{{ pageSize3 }}---- {{ pageNo3 }}---{{ total }}---{{ total % pageSize3 }}</p> -->
            <div class="preview-container">
                <el-icon class="preview-left" @click="showPrevious" @mouseover="handlerMouseoverLeft" @mouseout="handlerMouseoutLeft" title='上一条'>
                    <ArrowLeftBold :color="leftColor" size='80px' />
                </el-icon>
                <div class="preview-content">

                    <div class="showImg">
                        <viewer class="container" :images="clickImg">
                            <img :src="clickImg" v-if="PicImg.length > 0" />
                            <img src="../../../assets/20150907152206_77003.gif" v-if="PicImg.length < 1" />
                        </viewer>
                    </div>
                    <div class="imgLists" v-if="PicImg.length > 0">
                        <div class="imgDiv" v-for=" (recordsDataImg, index) in PicImg" :key="index" @click="selectImg(index)" :class="{ imgActiveBorder: border == index, imgBorder: border !== index }">
                            <img :src="recordsDataImg" alt="">
                        </div>
                    </div>
                    <div class="imgLists" v-if="PicImg.length < 1">
                        <div class="imgDiv" v-for=" (item, index) in 4" :key="index">
                            <img src="../../../assets/20150907152206_77003.gif" alt="" />
                        </div>
                    </div>
                </div>
                <el-icon class="preview-Right" @click="AddshowPrevious" @mouseover="handlerMouseoverRight" @mouseout="handlerMouseoutRight" title='下一条'>
                    <ArrowRightBold :color="rightColor" />
                </el-icon>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import moment from 'moment'
import { ref, onBeforeUnmount, watch, onMounted, computed } from "vue"
import {
    CaretBottom, CaretTop,
    ArrowLeftBold, ArrowRightBold
} from '@element-plus/icons-vue'
import ImgIcon from "./Icon-Img.vue"
import { useDetailsStore } from "@/stores/details";
// 获取设备小仓库
const detailsStore = useDetailsStore();
// 定义表格数据
const tableData = ref<any>([])
const PicImg = ref<any>([])
// 定义点击的那个图片
const clickImg = ref<any>('')
// 定义当前选中那个图片有边框
const border = ref(0)
// 左右箭头的颜色
const leftColor = ref("#404040")
const rightColor = ref("#A6A6A6")
// 传给父组件当前的条件
const emit = defineEmits(["dataToParent", 'dataToParent1', 'ChildChangePageSize'])
// 接收父组件传过来的条件
const props = defineProps(["recordsDataSource", 'CheckNameList', 'terminalIdentity', 'pageSize3', 'pageNo3', 'total'])
const prop = ref<any>(props)
const expands = ref<any>([])
// 弹框的显示与隐藏
const previewVisible = ref(false)
//存储图片的数据标识符
const currentDataIdentifier = ref('')
// 索引
const currentIndex = ref(0)
// 存储当前的条件(好品、坏品、异常品)
const selectOne = ref('坏品')
const selectTwo = ref('全部缺陷')
//定义（好拼、坏品、异常品）变量
const threeSelects = ref([
    { name: '全部', num: '', active: false },
    { name: '好品', num: 'OK', active: false },
    { name: '坏品', num: "NG", active: true },
    { name: '异常', num: "AB", active: false },
])
// 定义缺陷列表变量
const flawLists = ref<any>([])
const newRecordsDataSource = ref<any>([])
// 鼠标经过表格的图标
const openPreviewImg = (row: any) => {
    row.fullColor = '#F2994A'
}
// 鼠标经过表格的图标
const closePreviewImg = (row: any) => {
    row.fullColor = "#8C8C8C"
}
// 鼠标点击图片列表选择图片
const selectImg = (index: any) => {
    border.value = index
    clickImg.value = PicImg.value[index];

}
// 左箭头的事件
const showPrevious = () => {
    if (prop.value.pageNo3 == 1 && currentIndex.value == 0) {
        ElMessage({
            showClose: true,
            message: '已经最第一条数据了',
            type: 'warning',
        })
    } else {
        if (currentIndex.value > 0) {
            border.value = 0
            currentIndex.value--;

            currentDataIdentifier.value = prop.value.recordsDataSource[currentIndex.value].DataIdentifier;
            getImgList(currentDataIdentifier.value)
            PicImg.value = []
        } else {
            PicImg.value = []
            currentIndex.value = prop.value.pageSize3 - 1
            emit('ChildChangePageSize', prop.value.pageNo3 - 1);
            if (newRecordsDataSource.value.length > 0) {
                currentDataIdentifier.value = newRecordsDataSource.value[currentIndex.value]?.DataIdentifier;
                getImgList(currentDataIdentifier.value)
            }

        }
    }




}
// 右箭头的事件
const AddshowPrevious = () => {
    // 上一页的页码*每页几条+当前索引+1  <    总条数 
    if ((prop.value.pageNo3 - 1) * prop.value.pageSize3 + currentIndex.value + 1 < prop.value.total) {
        if (currentIndex.value < prop.value.recordsDataSource.length - 1) {
            border.value = 0
            currentIndex.value++;
            currentDataIdentifier.value = prop.value.recordsDataSource[currentIndex.value]?.DataIdentifier;
            getImgList(currentDataIdentifier.value)
            PicImg.value = []
        } else {
            // 最后一条数据了，需要切换至下一页，pageNo3+1
            // 将索引重新切换至0
            currentIndex.value = 0
            PicImg.value = []
            emit('ChildChangePageSize', prop.value.pageNo3 + 1);
            if (newRecordsDataSource.value.length > 0) {
                currentDataIdentifier.value = newRecordsDataSource.value[currentIndex.value]?.DataIdentifier;
                getImgList(currentDataIdentifier.value)
            }
        }
    } else {
        ElMessage({
            showClose: true,
            message: '已经是最后一条数据了',
            type: 'warning',
        })

    }
}
// 鼠标进入左箭头
const handlerMouseoverLeft = () => {
    //当当前页是第一页，并且是第一页第一条数据时，左箭头不会高亮，代表不能点击
    if (prop.value.pageNo3 == 1 && currentIndex.value == 0) {
        leftColor.value = "#404040"
    } else {
        // 只要当前不是第一页，左箭头就可以高亮，代表可以点击
        leftColor.value = '#F2994A'
    }
}
// 鼠标离开左箭头
const handlerMouseoutLeft = () => {
    leftColor.value = "#404040"
}
// 鼠标进入右箭头
const handlerMouseoverRight = () => {
    // 当余数为零，最后一页的最后一条数据不可高亮
    // 当余数不为零时，最后一页数据的索引等于余数的那一条不高亮

    // }
    // if (prop.value.total % prop.value.pageSize == 0) {
    //    if(prop.value.pageNo3 == Math.ceil(prop.value.total / prop.value.pageSize3)){

    //    }
    //     rightColor.value = '#404040'

    // } else if(prop.value.total % prop.value.pageSize !== 0) {
    //     rightColor.value = '#404040'
    // }else{
    rightColor.value = '#F2994A'
    // }

}

// 鼠标离开右箭头
const handlerMouseoutRight = () => {
    rightColor.value = "#404040"
}



// 格式化检测时间
const dateFormat = (row: any, column: any) => {
    const date = row[column.property]
    if (date === undefined) {
        return ''
    }
    // moment(date).format('YYYY-MM-DD HH:mm:ss')
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
// 格式化好品、坏品、异常品的
const fun = (CheckResult: any) => {
    const bad = { showName: '异常', color: '#FFBC00' }
    const lists = [
        { name: '检测正常', showName: '好品', color: '#1AA367' },
        { name: '检测错误', showName: '坏品', color: '#FF636B' }
    ]
    if (CheckResult) {
        const list = lists.find(item => item.name == CheckResult)
        if (list) return list
        if (!list) return bad
    }
}
const clickRowHandle = (row: any, column: any, event: any) => {
    // 点击表格行时的处理函数
    // 参数：
    // - row: 当前行数据
    // - column: 当前列数据
    // - event: 点击事件对象
    if (expands.value.includes(row.DataIdentifier)) {
        // 如果展开行中已经包含当前行的标识符
        expands.value = expands.value.filter((val: any) => val !== row.DataIdentifier);
        // 从展开行中移除当前行的标识符
    } else {
        // 如果展开行中不包含当前行的标识符
        expands.value.push(row.DataIdentifier);
        // 将当前行的标识符添加到展开行中
    }
}

// 选择好品、坏品、异常品的下拉框
const handler = (item: any) => {
    selectOne.value = item.name
    threeSelects.value.forEach((i: any) => {
        i.active = false
    });
    item.active = true
}
// 选择缺陷的下拉框
const handler1 = (item: any) => {
    selectTwo.value = item.name
    flawLists.value.forEach((i: any) => {
        i.active = false
    });
    item.active = true
}
const mouseOverComponent = ref(CaretBottom)
// 鼠标进入、离开表格中的好品、坏品、异常品的下拉框
const mouseOverSelectOne = () => {
    mouseOverComponent.value = CaretBottom
}
const mouseOutSelectOne = () => {
    mouseOverComponent.value = CaretTop
}
// 点击图片的事件
const openPreview = (row: any) => {
    previewVisible.value = true
    getImgList(row.DataIdentifier);
    currentIndex.value = prop.value.recordsDataSource.indexOf(row)
}

// 关闭弹框
const resetPreview = () => {
    previewVisible.value = false;
    border.value = 0;
    PicImg.value = [];
    currentIndex.value = 0;
}

// 发请求带着dataIdentifier 、terminalIdentity请求图片
const getImgList = async (dataIdentifier: any) => {
    await detailsStore.getImgs(prop.value.terminalIdentity, dataIdentifier)
    FunGetImg()
}
//从仓库拿数据，并且赋值
const FunGetImg = () => {
    const recordsDataImgList = ref(computed(() => detailsStore.$state.ImgList));
    if (recordsDataImgList.value.length > 0) {
        PicImg.value = recordsDataImgList.value;
        clickImg.value = PicImg.value[0]
    }
}
watch(currentIndex, (value) => {
    if (value === 0) {
        leftColor.value = '#404040'
    } else {
        leftColor.value = '#A6A6A6'
    }

})

// 监听选择要筛选的值(好品、坏品、异常品)
watch(selectOne, (value) => {
    const list: any = threeSelects.value.find(item => item.name == value)
    emit('dataToParent', list);
})
// 监听选择要筛选的值（缺陷）
watch(selectTwo, (value) => {
    emit('dataToParent1', value);
})
// 设置高亮
watch(prop.value.CheckNameList, (value) => {
    fun3()
})
const fun3 = () => {
    flawLists.value = prop.value.CheckNameList.map((item: any) => {
        return {
            num: prop.value.CheckNameList.indexOf(item) + 1,
            name: item,
            active: false
        };
    });
    const findList = flawLists.value.find((i: any) => i.name === selectTwo.value)
    if (findList) {
        findList.active = true
    }
}

watch(() => prop.value.recordsDataSource, (value) => {
    newRecordsDataSource.value = value
}, { deep: true })

// 处理表格数据
// const gettableData = () => {
//     tableData.value = prop.value.recordsDataSource.map((item: any) => {
//         return {
//             ...item,
//             fullColor: '#8C8C8C'
//         }
//     })
// }
onMounted(() => {
    setInterval(() => {
        fun3()
    }, 500)
})

</script>

<style scoped>
@media screen and (max-height: 1440px) {
    .tableBottom {
        height: 970px;
    }
}

@media screen and (max-height: 1080px) {
    .tableBottom {
        height: 600px;
    }
}

.tableBottom {
    width: 100%;
    height: 63vh;
}

.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}

.imageListDialog {
    width: 100%;
    height: 100vh;
    position: relative;
}

.preview-container {
    width: 100%;
    background: #222121;
}

.preview-content {
    background: #787878;
    display: flex;
    height: 91vh;
    width: 100%;
}

.showImg {
    width: 89.6%;
}

.showImg img {
    /* width: 100%;
     height: 100%;*/
    width: 0;
    height: 0;
}


.imgLists {
    width: 9.9%;
    overflow: scroll;
    margin-left: 12px;
    background: #787878;
}

::-webkit-scrollbar {
    display: none;
}

.imgLists .imgDiv {
    width: 100%;
    background: #222121;
    width: 100%;
    height: calc(94% / 8);
    cursor: pointer;
    text-align: center;
    margin-bottom: 8px;
}

.imgLists img {
    height: 100%;
    width: auto;
}

.imgActiveBorder {
    border: 2px solid #F2994A;
}

.imgBorder {}

/*左箭头*/
.preview-left {
    position: absolute;
    left: -44px;
}

.mousrStop {
    cursor: no-drop;
}

.preview-Right {
    position: absolute;
    left: calc(100% + 16px);
}

.preview-container i {
    top: calc(50% - 16px);
    color: white;
    font-size: 32px;
    cursor: pointer;
}

.custom-header {
    display: flex;
    align-items: center;
}

.el-icon--right {
    margin-left: 5px;
}

.allstyle {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 28px;
}

.point {
    display: block;
    border-radius: 50%;
    width: 8px;
    height: 8px;
    margin-right: 8px;
}

.el-dropdown-menu {
    max-height: 200px;
    overflow: auto;
}

.mousrPointer {
    cursor: pointer
}

.custom-dropdown-menu {
    max-height: 200px;
    overflow: auto;
    width: 120px;
}

.dropDown {
    padding: 0px 10px;
    height: 32px;
    line-height: 32px;
}

.dropDownActive {
    width: 100%;
    background: #f09a4e;
    color: #fff;
    border-radius: 6px;
}

:deep(li.el-dropdown-menu__item:hover) {
    color: #f09a4e;
    background: #fff;
}

.noLeftMargin {
    margin: 0px 5px 5px 0;
}

/*弹框*/
:deep(.el-dialog) {
    --el-dialog-margin-top: 0px;
    margin: auto;
    height: 91vh;
    margin-top: 3vh;
    background: #222121;
}

/*修改弹框的背景色*/
:deep(.el-dialog__body) {
    background: #787878;
    padding: 0;
}

/*修改弹框的头部*/
:deep(.el-dialog__header) {
    background: #222121;
    width: 100%;
    height: 0;
    padding: 0;
}


:deep(.el-dialog__headerbtn:hover .el-dialog__close) {
    color: #f9b141;
    transform: rotate(-90deg);
    transition: transform 0.3s ease;
}

:deep(.el-dialog__headerbtn) {
    top: -30px;
    right: -50px;
    padding: 0;
    width: 40px;
    height: 40px;
    background: #ffffff;
    border: none;
    outline: 0;
    cursor: pointer;
    font-size: 16px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    font-size: 25px;
}

/*左箭头隐藏*/
:deep(.viewer-prev) {
    display: none;

}

/*右箭头隐藏*/
:deep(.viewer-next) {
    display: none;

}

/*播放器隐藏*/
:deep(.viewer-play) {
    display: none;
}

/*将可缩放图片的z-index加大*/
:deep(.viewer-footer) {
    z-index: 900000;
}

:deep(.viewer-toolbar > ul > li:hover) {
    background: #F2994A;
}

::-webkit-scrollbar-track-piece {
    background: #d3dce6;
}

::-webkit-scrollbar {
    width: 20px;
}

::-webkit-scrollbar-thumb {
    background: #99a9bf;
    border-radius: 20px;
}
</style>